/*
 * @lc app=leetcode.cn id=671 lang=cpp
 *
 * [671] 二叉树中第二小的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
    TreeNode *findFirstGreaterTarget(TreeNode *root, const int target)
    {
        if (!root)
            return nullptr;
        if (root->val > target)
            return root;
        auto l = findFirstGreaterTarget(root->left, target);
        auto r = findFirstGreaterTarget(root->right, target);
        if (l && r)
        {
            if (l->val > r->val)
                return r;
            else
                return l;
        }
        else if (r)
        {
            return r;
        }
        else if (l)
            return l;
        else
            return nullptr;
    }

public:
    int findSecondMinimumValue(TreeNode *root)
    {
        if (!root || !root->left)
            return -1;
        auto ans = findFirstGreaterTarget(root, root->val);
        if(ans) return ans->val;
        return -1;
    }
};
// @lc code=end
